package com.zzb.framework.role.service;

import com.alibaba.fastjson.JSON;
import com.zzb.framework.event.EventHome;
import com.zzb.framework.role.dao.SysRoleDAO;
import com.zzb.framework.role.dao.SysRoleMenuDAO;
import com.zzb.framework.role.entity.IUser;
import com.zzb.framework.role.entity.SysRole;

import com.zzb.framework.common.BaseResponse;
import com.zzb.framework.common.BaseService;
import com.zzb.framework.common.ServiceException;
import com.zzb.framework.role.entity.SysRoleMenu;
import com.zzb.framework.validator.annotation.ValidatorEnabled;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* 角色表 service类
*/
@Service
public class SysRoleService extends BaseService<SysRoleDAO,SysRole> {
    private static final Logger logger = LoggerFactory.getLogger(SysRoleService.class);
    @Autowired
    private SysRoleDAO sysRoleDAO;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysRoleUserService sysRoleUserService;
    @Override
    public SysRoleDAO getDAO() {
        return sysRoleDAO;
    }
    /**删除角色表*/
    public BaseResponse deleteRole(String id,IUser operator) throws ServiceException{
        sysRoleMenuService.removeByRoleId(id);
        sysRoleUserService.deleteByRoleId(id);
        return deleteById(id);
    }
    /**保存角色表*/
    @ValidatorEnabled
    public BaseResponse<SysRole> saveRole(SysRole sysRole, IUser operator) throws ServiceException{
        logger.info("正在保存角色表["+ JSON.toJSONString(sysRole)+"]["+JSON.toJSONString(operator)+"]");
        if(StringUtils.isNotBlank(sysRole.getId() )){
            SysRole exist = getDAO().findByRoleCode(sysRole.getRoleCode());
            if(exist != null) return new BaseResponse<>(BaseResponse.FAIL,"创建角色失败，不能创建相同角色代码的角色");
        }
        return insertOrUpdate(sysRole,operator);
    }

    public List<SysRole> findByUserId(String userId){
        return getDAO().findByUserId(userId);
    }
    public SysRole findByRoleCode(String roleCode){return getDAO().findByRoleCode(roleCode);}
}
